<template>
    <div class="alarm-list-brief">
        <!-- 批量操作按钮 -->
        <div class="batch-actions" v-if="selectedAlarms.length > 0 && type === 'default'">
            <el-button type="primary" size="small" @click="handleBatchProcess" :loading="batchProcessing">
                {{ batchProcessing ? `处理中... (${processedCount}/${selectedAlarms.length})` : '批量处理' }}
            </el-button>
            <el-button type="warning" size="small" @click="handleBatchIgnore" :loading="batchIgnoring">
                {{ batchIgnoring ? `忽略中... (${processedCount}/${selectedAlarms.length})` : '批量忽略' }}
            </el-button>
            <span class="selected-count">已选择 {{ selectedAlarms.length }} 条告警</span>
        </div>

        <!-- 全选操作 -->
        <div class="select-all" v-if="visibleAlarms.length > 0 && type === 'default'">
            <el-checkbox v-model="isAllSelected" @change="handleSelectAll">
                全选当前页
            </el-checkbox>
        </div>

        <!-- 有告警数据时显示列表 -->
        <div v-for="alarm in visibleAlarms" :key="alarm.id" class="alarm-item" v-if="visibleAlarms.length > 0">
            <el-checkbox v-if="type === 'default'" v-model="alarm.selected" @change="handleSelectionChange(alarm)" />
            <div class="alarm-severity">
                <i class="fa fa-warning" :style="{ color: getSeverityColor(alarm.severityText) }"></i>
                <span :style="{ color: getSeverityColor(alarm.severityText) }">{{ alarm.severityText }}</span>
            </div>
            <div class="alarm-content">
                <div class="alarm-title">
                    {{ alarm.title }}
                </div>
                <div v-if="props.type === 'default'" class="alarm-info">
                    <div class="info-item">
                        {{ alarm.location }}
                    </div>
                    <div class="info-item">
                        {{ alarm.type }}
                    </div>
                    <div class="info-item">
                        {{ alarm.update_time }}
                    </div>
                </div>
            </div>
            <div class="alarm-actions">
                <el-button v-permission="'handle_exceptions'" type="primary" size="small"
                    @click="openProcessDialog(alarm)">
                    处理
                </el-button>
                <el-dropdown v-permission="'handle_exceptions'" trigger="click" @command="handleCommand($event, alarm)">
                    <el-button size="small">
                        <i class="fa fa-ellipsis-v"></i>
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="ignore">忽略告警</el-dropdown-item>
                            <el-dropdown-item command="detail">查看详情</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
        </div>

        <!-- 无告警数据时显示空状态 -->
        <div v-else class="empty-state">
            <el-empty description="暂无告警"></el-empty>
        </div>

        <!-- 使用封装的处理对话框组件 -->
        <ProcessDialog v-model:visible="processDialogVisible" :alarm="currentAlarm" @submit="handleProcessSubmit"
            @cancel="handleProcessCancel" />

        <!-- 告警详情对话框 -->
        <AlarmDetail v-model:visible="detailDialogVisible" :current-alarm="currentAlarm" @close="handleDetailClose" />

        <!-- 分页组件 - 只在有数据时显示且类型为default时显示 -->
        <div class="pagination-container" v-if="totalAlarms > 0 && props.type === 'default'">
            <el-pagination v-model:current-page="currentPage" :hide-on-single-page="true" v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="totalAlarms"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 批量处理对话框 -->
        <el-dialog v-model="batchProcessDialogVisible" title="批量处理告警" width="600px" :close-on-click-modal="false">
            <el-form :model="batchProcessForm" label-width="100px">
                <el-form-item label="处理说明">
                    <el-input v-model="batchProcessForm.description" type="textarea" :rows="4" placeholder="请输入处理说明" />
                </el-form-item>

                <el-form-item label="处理方式">
                    <el-radio-group v-model="batchProcessForm.processMode" :disabled="batchProcessing">
                        <el-radio value="parallel">
                            <div class="radio-content">
                                <div class="radio-title">并行处理（快速）</div>
                            </div>
                        </el-radio>
                        <el-radio value="serial">
                            <div class="radio-content">
                                <div class="radio-title">串行处理（稳定）</div>
                            </div>
                        </el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 串行处理时显示进度 -->
                <el-form-item v-if="batchProcessing && batchProcessForm.processMode === 'serial'" label="处理进度">
                    <el-progress :percentage="progressPercentage" :stroke-width="8" />
                    <p class="progress-text">正在处理第 {{ processedCount }} / {{ selectedAlarms.length }} 条告警</p>
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="batchProcessDialogVisible = false" :disabled="batchProcessing">取消</el-button>
                    <el-button type="primary" @click="confirmBatchProcess" :loading="batchProcessing">
                        {{ batchProcessing ? getProcessingText('处理') : '确认处理' }}
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 批量忽略确认对话框 -->
        <el-dialog v-model="batchIgnoreDialogVisible" title="批量忽略告警" width="500px" :close-on-click-modal="false">
            <div class="ignore-content">
                <p>确定要忽略选中的 {{ selectedAlarms.length }} 条告警吗？</p>

                <el-form label-width="80px">
                    <el-form-item label="处理方式">
                        <el-radio-group v-model="batchIgnoreForm.processMode" :disabled="batchIgnoring">
                            <el-radio value="parallel">
                                并行忽略（快速）
                            </el-radio>
                            <el-radio value="serial">
                                串行忽略（稳定）
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>

                <!-- 处理进度显示 -->
                <div v-if="batchIgnoring" class="processing-info">
                    <el-progress :percentage="progressPercentage" :stroke-width="6" />
                    <p class="progress-text">
                        {{ batchIgnoreForm.processMode === 'serial' ?
                            `正在处理第 ${processedCount} / ${selectedAlarms.length} 条告警...` :
                            '正在并行处理所有告警...' }}
                    </p>
                </div>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="batchIgnoreDialogVisible = false" :disabled="batchIgnoring">取消</el-button>
                    <el-button type="warning" @click="confirmBatchIgnore" :loading="batchIgnoring">
                        {{ batchIgnoring ? getProcessingText('忽略') : '确认忽略' }}
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
// 导入处理对话框组件
import ProcessDialog from './components/ProcessDialog.vue'
// 导入告警详情组件
import AlarmDetail from './components/AlarmDetail.vue'
// 导入API
import { updateEventApi } from '@/api/event'
import { handleError } from '@/utils/handleError'

const props = defineProps({
    alarms: {
        type: Array,
        default: () => []
    },
    type: {
        type: String,
        default: 'default'
    },
})

// 状态管理
const processDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentAlarm = ref(null)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const emit = defineEmits(['refreshData'])

// 选中的告警
const selectedAlarms = ref([])

// 批量处理状态
const batchProcessing = ref(false)
const batchIgnoring = ref(false)
const processedCount = ref(0)

// 批量处理表单
const batchProcessForm = ref({
    description: '',
    processMode: 'parallel' // 默认并行
})

// 批量忽略表单
const batchIgnoreForm = ref({
    processMode: 'parallel' // 默认并行
})

// 进度百分比
const progressPercentage = computed(() => {
    if (selectedAlarms.value.length === 0) return 0
    return Math.round((processedCount.value / selectedAlarms.value.length) * 100)
})

// 获取处理中的文本
const getProcessingText = (action) => {
    const mode = action === '处理' ? batchProcessForm.value.processMode : batchIgnoreForm.value.processMode
    const modeText = mode === 'serial' ? '串行' : '并行'

    if (mode === 'serial') {
        return `${modeText}${action}中... (${processedCount.value}/${selectedAlarms.value.length})`
    } else {
        return `${modeText}${action}中...`
    }
}

// 总告警数量
const totalAlarms = computed(() => {
    return props.alarms.length
})

// 根据分页或类型设置显示的告警
const visibleAlarms = computed(() => {
    if (props.type !== 'default') {
        return props.alarms
    }
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    return props.alarms.slice(startIndex, endIndex)
})

// 当告警数量变化时，可能需要调整当前页
watch(() => props.alarms.length, (newLength) => {
    const maxPage = Math.ceil(newLength / pageSize.value) || 1
    if (currentPage.value > maxPage) {
        currentPage.value = maxPage
    }
})

// 获取告警级别对应的颜色
const getSeverityColor = (severity) => {
    const colors = {
        '严重': '#E85656',
        '警告': '#F5A623',
        '提示': '#666'
    }
    return colors[severity] || '#666'
}

// 打开处理对话框
const openProcessDialog = (alarm) => {
    currentAlarm.value = alarm
    processDialogVisible.value = true
}

// 打开详情对话框
const openDetailDialog = (alarm) => {
    currentAlarm.value = alarm
    detailDialogVisible.value = true
}

// 关闭详情对话框
const handleDetailClose = () => {
    detailDialogVisible.value = false
    setTimeout(() => {
        if (!processDialogVisible.value) {
            currentAlarm.value = null
        }
    }, 300)
}

// 提交处理
const handleProcessSubmit = async (processData) => {
    try {
        await updateEventApi({
            id: processData.alarmId,
            status: 2,
            info: processData.description
        })
        emit('refreshData')
        ElMessage({
            type: 'success',
            message: '告警处理成功'
        })
    } catch (error) {
        handleError(error, '处理失败，请稍后重试')
    }
}

// 取消处理
const handleProcessCancel = () => {
    processDialogVisible.value = false
    setTimeout(() => {
        if (!detailDialogVisible.value) {
            currentAlarm.value = null
        }
    }, 300)
}

// 分页大小变化
const handleSizeChange = (size) => {
    pageSize.value = size
}

// 当前页变化
const handleCurrentChange = (page) => {
    currentPage.value = page
}

// 处理选择变化
const handleSelectionChange = (alarm) => {
    if (alarm.selected) {
        selectedAlarms.value.push(alarm)
    } else {
        const index = selectedAlarms.value.findIndex(item => item.id === alarm.id)
        if (index !== -1) {
            selectedAlarms.value.splice(index, 1)
        }
    }
}

// 批量处理对话框
const batchProcessDialogVisible = ref(false)

// 批量忽略确认对话框
const batchIgnoreDialogVisible = ref(false)

// 全选状态
const isAllSelected = ref(false)

// 处理全选
const handleSelectAll = (val) => {
    visibleAlarms.value.forEach(alarm => {
        alarm.selected = val
        if (val) {
            if (!selectedAlarms.value.find(item => item.id === alarm.id)) {
                selectedAlarms.value.push(alarm)
            }
        } else {
            const index = selectedAlarms.value.findIndex(item => item.id === alarm.id)
            if (index !== -1) {
                selectedAlarms.value.splice(index, 1)
            }
        }
    })
}

// 监听选择变化，更新全选状态
watch(selectedAlarms, (newVal) => {
    isAllSelected.value = visibleAlarms.value.length > 0 &&
        visibleAlarms.value.every(alarm =>
            newVal.some(selected => selected.id === alarm.id)
        )
}, { deep: true })

// 打开批量处理对话框
const handleBatchProcess = () => {
    batchProcessForm.value.description = ''
    batchProcessForm.value.processMode = 'parallel'
    batchProcessDialogVisible.value = true
}

// 串行处理函数
const processSerial = async (alarms, status, description) => {
    let successCount = 0
    let failureCount = 0
    const failedAlarms = []

    for (let i = 0; i < alarms.length; i++) {
        const alarm = alarms[i]
        try {
            await updateEventApi({
                id: alarm.id,
                status: status,
                info: description
            })
            successCount++
        } catch (error) {
            console.error(`处理告警 ${alarm.id} 失败:`, error)
            failureCount++
            failedAlarms.push(alarm)
        }

        processedCount.value = i + 1
        // 添加小延迟，避免请求过于频繁
        await new Promise(resolve => setTimeout(resolve, 200))
    }

    return { successCount, failureCount, failedAlarms }
}

// 并行处理函数
const processParallel = async (alarms, status, description) => {
    const promises = alarms.map(alarm =>
        updateEventApi({
            id: alarm.id,
            status: status,
            info: description
        }).catch(error => {
            console.error(`处理告警 ${alarm.id} 失败:`, error)
            return { error, alarm }
        })
    )

    const results = await Promise.allSettled(promises)

    let successCount = 0
    let failureCount = 0
    const failedAlarms = []

    results.forEach((result, index) => {
        if (result.status === 'fulfilled' && !result.value?.error) {
            successCount++
        } else {
            failureCount++
            failedAlarms.push(alarms[index])
        }
    })

    return { successCount, failureCount, failedAlarms }
}

// 批量处理确认
const confirmBatchProcess = async () => {
    batchProcessing.value = true
    processedCount.value = 0

    try {
        const { successCount, failureCount } = batchProcessForm.value.processMode === 'serial'
            ? await processSerial(selectedAlarms.value, 2, batchProcessForm.value.description || '批量处理')
            : await processParallel(selectedAlarms.value, 2, batchProcessForm.value.description || '批量处理')

        // 显示结果
        if (failureCount === 0) {
            ElMessage({
                type: 'success',
                message: `成功处理 ${successCount} 条告警`
            })
        } else {
            ElMessage({
                type: 'warning',
                message: `处理完成：成功 ${successCount} 条，失败 ${failureCount} 条`
            })
        }

    } catch (error) {
        handleError(error, '批量处理出错，请稍后重试')
    } finally {
        // 清理状态
        selectedAlarms.value.forEach(alarm => {
            alarm.selected = false
        })
        selectedAlarms.value = []
        isAllSelected.value = false
        processedCount.value = 0
        batchProcessing.value = false
        batchProcessDialogVisible.value = false
        emit('refreshData')
    }
}

// 打开批量忽略确认对话框
const handleBatchIgnore = () => {
    batchIgnoreForm.value.processMode = 'parallel'
    batchIgnoreDialogVisible.value = true
}

// 批量忽略确认
const confirmBatchIgnore = async () => {
    batchIgnoring.value = true
    processedCount.value = 0

    try {
        const { successCount, failureCount } = batchIgnoreForm.value.processMode === 'serial'
            ? await processSerial(selectedAlarms.value, 3, '批量忽略')
            : await processParallel(selectedAlarms.value, 3, '批量忽略')

        // 显示结果
        if (failureCount === 0) {
            ElMessage({
                type: 'success',
                message: `成功忽略 ${successCount} 条告警`
            })
        } else {
            ElMessage({
                type: 'warning',
                message: `忽略完成：成功 ${successCount} 条，失败 ${failureCount} 条`
            })
        }

    } catch (error) {
        handleError(error, '批量忽略出错，请稍后重试')
    } finally {
        // 清理状态
        selectedAlarms.value.forEach(alarm => {
            alarm.selected = false
        })
        selectedAlarms.value = []
        isAllSelected.value = false
        processedCount.value = 0
        batchIgnoring.value = false
        batchIgnoreDialogVisible.value = false
        emit('refreshData')
    }
}

const handleCommand = async (command, alarm) => {
    if (command === 'ignore') {
        try {
            await updateEventApi({
                id: alarm.id,
                status: 3,
                info: '用户手动忽略'
            })
            emit('refreshData')
            ElMessage({
                type: 'success',
                message: '已忽略该告警'
            })
        } catch (error) {
            handleError(error, '忽略告警失败')
        }
    } else if (command === 'detail') {
        openDetailDialog(alarm)
    }
}
</script>

<style scoped>
.alarm-list-brief {
    display: flex;
    flex-direction: column;
    gap: 12px;
    width: 100%;
}

.alarm-item {
    width: 100%;
    display: flex;
    align-items: center;
    padding: 16px;
    background: var(--el-bg-color-page);
    border-radius: 4px;
    gap: 16px;
}

.alarm-severity {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
    min-width: 60px;
}

.alarm-content {
    flex: 1;
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.alarm-title {
    width: 100%;
    font-weight: 500;
    font-size: 14px;
}

.alarm-info {
    display: flex;
    gap: 16px;
    color: var(--el-text-color-secondary);
    font-size: 13px;
}

.info-item {
    display: flex;
    align-items: center;
    gap: 4px;
}

.info-item i {
    font-size: 14px;
}

.alarm-actions {
    display: flex;
    gap: 8px;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 10px 0;
}

.empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 500px;
    border-radius: 4px;
    padding: 20px;
}

.batch-actions {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 12px;
    padding: 8px 16px;
    background-color: var(--el-color-primary-light-9);
    border-radius: 4px;
}

.selected-count {
    color: var(--el-text-color-secondary);
    font-size: 14px;
}

.select-all {
    margin-bottom: 8px;
    padding: 0 16px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

/* 新增样式 */
.radio-content {
    margin-left: 8px;
}

.radio-title {
    font-weight: 500;
    color: var(--el-text-color-primary);
}

.radio-desc {
    font-size: 12px;
    color: var(--el-text-color-secondary);
}

.processing-info {
    margin: 16px 0;
}

.progress-text {
    margin: 8px 0 0 0;
    font-size: 14px;
    color: var(--el-text-color-secondary);
    text-align: center;
}

.ignore-content p {
    margin-bottom: 20px;
    font-size: 16px;
}
</style>